package io.github.uicdb.badskill.codec;

import com.google.gson.*;
import net.minecraft.nbt.CompoundTag;
import net.minecraft.nbt.Tag;
import net.minecraft.world.item.ItemStack;
import net.minecraftforge.common.crafting.CraftingHelper;
import net.minecraftforge.registries.ForgeRegistries;

import java.lang.reflect.Type;
import java.util.Objects;

public class ItemStackCodec implements JsonDeserializer<ItemStack>, JsonSerializer<ItemStack> {
    public static final ItemStackCodec INSTANCE=new ItemStackCodec();
    @Override
    public ItemStack deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context) throws JsonParseException {
        return CraftingHelper.getItemStack(json.getAsJsonObject(),true);
    }

    @Override
    public JsonElement serialize(ItemStack stack, Type typeOfSrc, JsonSerializationContext context) {
        JsonObject json = new JsonObject();
        json.addProperty("item", Objects.requireNonNull(ForgeRegistries.ITEMS.getKey(stack.getItem()), "Can't serialize ItemStack: Item has no registry name: " + stack.getItem()).toString());
        json.addProperty("count", stack.getCount());
        CompoundTag stackTag = stack.hasTag() ? stack.getTag() : null;
        Tag capsTag = forgeCaps(stack);
        if (stackTag != null || capsTag != null) {
            // Need to make a copy, so the stack is not modified.
            CompoundTag resultTag = stackTag == null ? new CompoundTag() : stackTag.copy();
            if (capsTag != null) resultTag.put("ForgeCaps", capsTag);
            json.addProperty("nbt", resultTag.toString());
        }
        return json;
    }


    protected Tag forgeCaps(ItemStack stack) {
        CompoundTag nbt = stack.serializeNBT();
        if (nbt.contains("ForgeCaps") && (!(nbt.get("ForgeCaps") instanceof CompoundTag cmp) || !cmp.isEmpty())) {
            return nbt.get("ForgeCaps");
        } else {
            return null;
        }
    }
}
